<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="600px"
      @closed="resetForm('form')"
    >
      <div>
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="用户类型" prop="deName">
            <el-input v-model.trim="form.deName"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" v-preventReClick @click="submitForm('form')"
          >提 交</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  tbDictDetailAdd,
  tbDictDetailUpdate,
} from '@/api/admin/system/dictionaryDet.js'
export default {
  data() {
    return {
      title: '新增',
      dialogVisible: false,
      form: {
        deName: '',
        content: '',
        deValue: '',
        dictId: '0c64ee4896364b6f8bc3314e768ae676',
      },
      rules: {
        deName: [
          { required: true, message: '请输入用户类型', trigger: 'blur' },
        ],
      },
    }
  },
  props: ['tableData'],
  mounted() {
    this.$bus.$on('showDialogUserTypeAdd', this.init)
  },
  beforeDestroy() {
    this.$bus.$off('showDialogUserTypeAdd')
  },
  methods: {
    //显示弹窗
    init(row) {
      if (row) {
        this.form = { ...this.form, ...row }
        this.$set(this.form, 'id', row.id)
      } else {
        this.form = this.$options.data().form
        this.$delete(this.form, 'id')
      }
      this.title = row ? '编辑' : '新增'
      this.dialogVisible = true
    },
    submitForm(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          this.title == '新增' ? this.add() : this.edit()
        }
      })
    },
    add() {
      let arr = this.tableData.map((v) => v.deValue)
      this.form.deValue = Math.max(...arr) + 10
      tbDictDetailAdd(this.form).then((res) => {
        this.done()
      })
    },
    edit() {
      tbDictDetailUpdate(this.form).then((res) => {
        this.done()
      })
    },
    done() {
      this.dialogVisible = false
      this.$bus.$emit('refreshUserTypeList')
      this.$message({
        message: '操作成功',
        type: 'success',
      })
    },
    resetForm(form) {
      this.$refs[form].resetFields()
    },
  },
}
</script>